" GENERAL: Globle General Settings {{{1
set nocompatible  "设置backspace的工作方式
filetype plugin indent on        "自动缩进 :h filetype
syntax on  " 开启语法高亮
colorscheme default "vim配置方案 :echo $VIM  :echo $VIMRUNTIME
set t_Co=256
set   number  " 显示行号
set   hls "搜索时高亮显示被找到的文本
set   scrolloff=3 " 上下可视行数
set   incsearch   " 搜索时高亮显示被找到的文本
set   ignorecase smartcase "搜索时默认不区分大小写，只有搜索关键字中出现一个大字母时才区分大小写
set   enc=utf-8  "编码设置
" set   fileencodings=ucs-bom,utf-8,cp936,gb18030,big5,euc-jp,euc-kr,latin1 "编码自动识别
set   mouse=a "鼠标普通模式
set   selection=exclusive
set   autoread                   "Vim 之外修改自动重新读入
set   autowrite                  "自动把内容写回文件
set   cindent                    "根据 C 缩进规则应有的缩进距离
set   cinoptions=:4              "影响 'cindent' 重新缩进 C 程序行的方式
set   nobackup                   "不保留备份文件
set   expandtab                  "插入 <Tab> 时使用合适数量的空格
set   tabstop=4                  "<Tab> 代表的空格数
set   softtabstop=4              "使得按退格键时可以一次删掉 4 个空格
set   history=1000               "命令历史显示1000条
set   textwidth=160              "达到80行，自动换行"
set   foldenable                 "折叠
set   foldmethod=marker          "标志用于指定折叠
set   helplang=cn                "以逗号分隔的语言列表
set   laststatus=2               "最后一个窗口何时有状态行 0: 永不 1: 只有在有至少两个窗口时 2: 总是
set   pumheight=10               "插入模式补全的弹出菜单显示项目的最大数目
set   ruler                      "显示光标位置的行号和列号，逗号分隔
set   sidescroll=12              "光标左右两侧最少保留的屏幕列数
set   shiftwidth=4               "缩进每一步使用的空白数目
set   smartindent                "开启新行时使用智能自动缩进
set   wildignore=*.bak,*.o,*~    "文件和目录名的补全中忽略符合其中任何模式的文件
set   wildmenu                   "在命令行的上方显示可能的匹配，然后高亮首个匹配
set   wildmode=list:longest,full "指定的字符所用的补全模式 :h wildmode
set   noswapfile                 "缓冲区不使用交换文件
set   nowrap                     "设置不折行
set   cursorline                 "突出当前行
set   magic                      "正则表达式匹配形式
set   clipboard^=unnamed,unnamedplus "与外界共用×与+剪贴板
set   pastetoggle=<F3>           "Insert模式粘贴时保持原格式
set   backspace=indent,eol,start "设置backspace的工作方式
set   noerrorbells               "关闭错误信息响铃
set   novisualbell               "关闭使用可视响铃代替呼叫
set   t_vb=                      "置空错误铃声的终端代码
set   showmatch                  "插入括号时，短暂地跳转到匹配的对应括号
set   tags=tags;
" set   nowrapscan                 "禁止在搜索到文件两端时重新搜索
" set   autochdir
" set   cursorline "选中行出现下划线
map qq :qa!<CR> "多窗口不保存关闭
map ww :wqa!<CR> "多窗口保存关闭
"vim自动打开跳到上次的光标位置
if has("autocmd")
	        au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
endif
" 自动去除尾行空格和tab
" From: Vigil <vim5632@rainslide.net>
function RemoveTrailingWhitespace()
	if &ft != "diff"
		let b:curcol = col(".")
		let b:curline = line(".")
		silent! %s/\s\+$//
		call cursor(b:curline, b:curcol)
	endif
endfunction
"autocmd BufWritePre * call RemoveTrailingWhitespace()
set list lcs=tab:\¦\ ,trail:·,extends:»,precedes:«
map <C-L> :ter<CR>
"}}}

" Switching between buffers{{{1
nnoremap <C-w> <C-W>w
"}}}

" PLUG: Plug Settings {{{1
call plug#begin('~/.vim/plugged')
Plug 'https://gitee.com/yanzhongqian/taglist.vim.git'
"Plug 'https://gitee.com/yanzhongqian/nerdtree.git'
Plug 'https://gitee.com/yanzhongqian/nerdcommenter.git'
Plug 'https://gitee.com/yanzhongqian/vim-airline.git'
Plug 'https://gitee.com/yanzhongqian/vim-powerline.git'
Plug 'https://gitee.com/yanzhongqian/autoload_cscope.vim.git'
"Plug 'https://gitee.com/yanzhongqian/vim-gutentags.git'
"Plug 'https://gitee.com/yanzhongqian/gutentags_plus.git'
"Plug 'https://gitee.com/yanzhongqian/vim-preview.git'
"Plug 'https://gitee.com/yanzhongqian/vim-cpp-enhanced-highlight.git'
"Plug 'https://gitee.com/yanzhongqian/vim-colorschemes.git'
Plug 'https://gitee.com/yanzhongqian/LeaderF.git', { 'do': ':LeaderfInstallCExtension' }
"Plug 'https://gitee.com/zgpio/onedark.vim.git'
Plug 'https://gitee.com/yanzhongqian/AutoComplPop.git'
Plug 'https://gitee.com/yanzhongqian/OmniCppComplete.git'
Plug 'https://gitee.com/yanzhongqian/vim-interestingwords.git'
Plug 'https://gitee.com/yanzhongqian/TagHighlight.git'
"Plug 'https://gitee.com/yanzhongqian/taghighlight-automirror.git'
" Plug 'https://gitee.com/yanzhongqian/rainbow.git'
Plug 'https://gitee.com/yanzhongqian/ale.git'
Plug 'https://gitee.com/yanzhongqian/ultisnips.git'
Plug 'https://gitee.com/yanzhongqian/vim-snippets.git'
call plug#end()
"}}}

" map: set mapleader to ',' {{{1
let mapleader=','
"}}}

" PLUG: TagList Settings {{{1
"taglist config
let Tlist_Show_One_File           = 1 " 只显示当前文件的tags
let Tlist_Exit_OnlyWindow         = 1 " 如果Tlist窗口是最后一个窗口则退出Vim
let Tlist_Use_Left_Window         = 1 " 在左侧窗口中显示
let Tlist_File_Fold_Auto_Close    = 1 " 自动折叠
let Tlist_Auto_Update             = 1 " 自动更新
map <F2> :TlistToggle<CR>
"}}}

" PLUG: Nerdtree Settings {{{1
nnoremap <F3> :NERDTreeFind<CR>
let g:NERDTreeWinPos="right"
let g:NERDTreeWinSize=25
let g:NERDTreeShowLineNumbers=1
let g:NERDTreeQuitOnOpen=1
"}}}

" PLUG: Commenter Settings {{{1
" commenter
let g:NERDSpaceDelims            = 1      " 在注释符号后加一个空格
let g:NERDCompactSexyComs        = 1      " 紧凑排布多行注释
let g:NERDDefaultAlign           = 'left' " 逐行注释左对齐
let g:NERDAltDelims_java         = 1      " JAVA 语言使用默认的注释符号
let g:NERDCustomDelimiters       = {'c': {'left': '/*', 'right': '*/'}} " C 语言注释符号
let g:NERDCommentEmptyLines      = 1      " 允许空行注释
let g:NERDTrimTrailingWhitespace = 1      " 取消注释时删除行尾空格
let g:NERDToggleCheckAllLines    = 1      " 检查选中的行操作是否成功
map <F12> <plug>NERDCommenterSexy         " 选中注释
map <c-F12> <plug>NERDCommenterUncomment  " 选中取消注释
"}}}

" PLUG: AirLine Settings {{{1
"开启airline
let g:airline_powerline_fonts = 1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#buffer_nr_show = 1
let g:airline#extensions#tabline#formatter = 'unique_tail'
" 关闭空白符检测
let g:airline#extensions#whitespace#enabled = 0
let g:airline#extensions#whitespace#symbol = '!'

if !exists('g:airline_symbols')
	  let g:airline_symbols = {}
endif

let g:airline_left_sep = '▶'
let g:airline_right_sep = '◀'
let g:airline_symbols.crypt = '🔒'
let g:airline_symbols.linenr = '¶'
let g:airline_symbols.maxlinenr = '☰'
let g:airline_symbols.branch = '⎇'
let g:airline_symbols.paste = '∥'
let g:airline_symbols.spell = 'Ꞩ'
let g:airline_symbols.notexists = '∄'
let g:airline_symbols.whitespace = 'Ξ'

map <c-Left> :bp<CR>    " 切换到上一个
map <c-Right> :bn<CR>   " 切换到下一个
noremap <F4> :bd<CR>    " 关闭当前窗口
map 11 :b1<CR>          " 切换到编号1
map 22 :b2<CR>          " 切换到编号2
map 33 :b3<CR>          " 切换到编号3
map 44 :b4<CR>          " 切换到编号4
map 55 :b5<CR>          " 切换到编号5
map 66 :b6<CR>          " 切换到编号6
map 77 :b7<CR>          " 切换到编号7
map 88 :b8<CR>          " 切换到编号8
map 99 :b9<CR>          " 切换到编号9
map 00 :b10<CR>         " 切换到编号10
"}}}

" PLUG: gutentags Settings {{{1
" dont't auto gen tags
"let g:Lf_GtagsAutoGenerate = 0
"map <c-]> g<c-]>  "ctags跳转不自动选择
" gutentags 搜索工程目录的标志，碰到这些文件/目录名就停止向上一级目录递归
"let g:gutentags_project_root = ['.root', '.svn', '.git', '.hg', '.project', 'test']
" 所生成的数据文件的名称
"let g:gutentags_ctags_tagfile = '.tags'
" 同时开启 ctags 和 gtags 支持：
"let g:gutentags_modules = []
"if executable('ctags')
"	let g:gutentags_modules += ['ctags']
"endif
"if executable('gtags-cscope') && executable('gtags')
"	let g:gutentags_modules += ['gtags_cscope']
"endif
" 将自动生成的 tags 文件全部放入 ~/.cache/tags 目录中，避免污染工程目录
"let s:vim_tags = expand('~/.cache/tags')
"let g:gutentags_cache_dir = s:vim_tags
" 配置 ctags 的参数
"let g:gutentags_cache_dir = expand('~/.cache/tags')
"let g:gutentags_ctags_extra_args = ['--fields=+niazS', '--extra=+q']
"let g:gutentags_ctags_extra_args += ['--c++-kinds=+px']
"let g:gutentags_ctags_extra_args += ['--c-kinds=+px']
" 检测 ~/.cache/tags 不存在就新建
"if !isdirectory(s:vim_tags)
"   silent! call mkdir(s:vim_tags, 'p')
"endif
" 禁用 gutentags 自动加载 gtags 数据库的行为
"let g:gutentags_auto_add_gtags_cscope = 0
"
" gtags-cscope
"s：查找C代码符号
"g：查找本定义
"c：查找调用本函数的函数
"t：查找本字符串
"e：查找本egrep模式
"f：查找本文件
"i：查找包含本文件的文件
"d：查找本函数调用的函数
"let g:gutentags_plus_nomap = 1
"noremap <silent> <c-\>s :GscopeFind s <C-R><C-W><cr>
"noremap <silent> <c-\>g :GscopeFind g <C-R><C-W><cr>
"noremap <silent> <c-\>c :GscopeFind c <C-R><C-W><cr>
"noremap <silent> <c-\>t :GscopeFind t <C-R><C-W><cr>
"noremap <silent> <c-\>e :GscopeFind e <C-R><C-W><cr>
"noremap <silent> <c-\>f :GscopeFind f <C-R>=expand("<cfile>")<cr><cr>
"noremap <silent> <c-\>i :GscopeFind i <C-R>=expand("<cfile>")<cr><cr>
"noremap <silent> <c-\>d :GscopeFind d <C-R><C-W><cr>
"noremap <silent> <c-\>a :GscopeFind a <C-R><C-W><cr>

" preview
"autocmd FileType qf nnoremap <silent><buffer> p :PreviewQuickfix<cr>
"autocmd FileType qf nnoremap <silent><buffer> P :PreviewClose<cr>
"}}}

" PLUG: highlight Settings {{{1
"hight
let g:cpp_class_scope_highlight = 1
let g:cpp_member_variable_highlight = 1
let g:cpp_class_decl_highlight = 1
let g:cpp_posix_standard = 1
let g:cpp_experimental_simple_template_highlight = 1
let g:cpp_experimental_template_highlight = 1
let g:cpp_concepts_highlight = 1
let g:cpp_no_function_highlight = 1
"}}}

" PLUG: TagHighlight Settings {{{1
"hi Normal   ctermfg=13
"SlateBlue3	#5f5faf	rgb(95,95,175)	hsl(240,33%,52%)
hi CTagsGlobalVariable ctermfg=97
"DarkSeaGreen4	#5f875f	rgb(95,135,95)	hsl(120,17%,45%)
hi CTagsDefinedName ctermfg=65
hi CTagsEnumeratorName ctermfg=139
hi CTagsEnumerationName ctermfg=139
hi CTagsEnumerationValue ctermfg=139
hi CTagsUnion   ctermfg=81
"}}}

" PLUG: leaderf Settings {{{1
"Leaderf
"<C-R>  switch between fuzzy search mode and regex mode
"<C-F>  switch between full path search mode and name only search mode
"  file                search files
"  tag                 navigate tags using the tags file
"  function            navigate functions or methods in the buffer
"  mru                 search most recently used files
"  searchHistory       execute the search command in the history
"  cmdHistory          execute the command in the history
"  help                navigate the help tags
"  line                search a line in the buffer
"  colorscheme         switch between colorschemes
"  gtags               navigate tags using the gtags
"  self                execute the commands of itself
"  bufTag              navigate tags in the buffer
"  buffer              search buffers
"  rg                  grep using rg
"  filetype            navigate the filetype
"  command             execute built-in/user-defined Ex commands.
"  window              search windows.
"  quickfix            navigate the quickfix.
"  loclist             navigate the location list.
let g:Lf_ShortcutF = '<c-p>' " 文件快速搜索 函数,宏,变量快速搜索
noremap <leader>fb :<C-U><C-R>=printf("Leaderf buffer %s", "")<CR><CR>
noremap <leader>ft :<C-U><C-R>=printf("Leaderf bufTag %s", "")<CR><CR>
noremap <leader>fl :<C-U><C-R>=printf("Leaderf line %s", "")<CR><CR>
noremap <leader>ff :<C-U><C-R>=printf("Leaderf function %s", "")<CR><CR>
noremap <leader>m :<C-U><C-R>=printf("Leaderf mru %s", "")<CR><CR>
" tags for search defination
noremap <C-g> :LeaderfTagCword<CR>
" search string in current buf, like do grep in this file
noremap <C-B> :<C-U><C-R>=printf("Leaderf! rg --current-buffer -e %s ", expand("<cword>"))<CR>
" search string, like do grep
noremap <C-k> :<C-U><C-R>=printf("Leaderf! rg -e %s -g '*.{c,h,py}'", expand("<cword>"))<CR>
" only search in .c and .h, or you can use -t c -t py, rg --type-list show all
noremap <C-j> :<C-U><C-R>=printf("Leaderf! rg -e %s -g '*.[ch]'", expand("<cword>"))<CR>
" not match
" noremap <C-j> :<C-U><C-R>=printf("Leaderf! rg -e %s -g '!*.c'", expand("<cword>"))<CR>
"
" search visually selected text literally
xnoremap gf :<C-U><C-R>=printf("Leaderf! rg -F -e %s ", leaderf#Rg#visual())<CR>
" re do Leaderf
noremap go :<C-U>Leaderf! rg --recall<CR>

let g:Lf_StlSeparator = { 'left': '', 'right': '', 'font': '' }
let g:Lf_RootMarkers = ['.project', '.root', '.svn', '.git', 'test', 'work']
let g:Lf_WorkingDirectoryMode = 'Ac'
let g:Lf_WindowHeight = 0.30
let g:Lf_ShowRelativePath = 0
let g:Lf_HideHelp = 1
let g:Lf_StlColorscheme = 'powerline'
let g:Lf_PreviewInPopup = 1
let g:Lf_PreviewResult = {
        \ 'File': 0,
        \ 'Buffer': 0,
        \ 'Mru': 0,
        \ 'Tag': 1,
        \ 'BufTag': 1,
        \ 'Function': 1,
        \ 'Line': 1,
        \ 'Colorscheme': 0,
        \ 'Rg': 1,
        \ 'Gtags': 0
        \}
"let g:Lf_CacheDirectory = expand('~/.vim/cache')
"
" should use `Leaderf gtags --update` first
"let g:Lf_GtagsAutoGenerate = 1
"let g:Lf_Gtagslabel = 'native-pygments'
"let g:Lf_GtagsSource = 1
"noremap <leader>fr :<C-U><C-R>=printf("Leaderf! gtags -r %s --auto-jump", expand("<cword>"))<CR><CR>
"noremap <leader>fd :<C-U><C-R>=printf("Leaderf! gtags -d %s --auto-jump", expand("<cword>"))<CR><CR>
"noremap <leader>fo :<C-U><C-R>=printf("Leaderf! gtags --recall %s", "")<CR><CR>
"noremap <leader>fn :<C-U><C-R>=printf("Leaderf gtags --next %s", "")<CR><CR>
"noremap <leader>fp :<C-U><C-R>=printf("Leaderf gtags --previous %s", "")<CR><CR>
"}}}

" PLUG: omnicppcomplete Settings {{{1
"-- omnicppcomplete setting --
" 按下F7自动补全代码，注意该映射语句后不能有其他字符，包括tab；否则按下F3会自动补全一些乱码
" imap <F7> <C-X><C-O>
"按下F8根据头文件内关键字补全
" imap <F8> <C-X><C-I>
"set tags+=g:gutentags_cache_dir "添加ctags绝对路径
set completeopt=menu,menuone " 关掉智能补全时的预览窗口
let OmniCpp_MayCompleteDot = 1 " autocomplete with .
let OmniCpp_MayCompleteArrow = 1 " autocomplete with ->
let OmniCpp_MayCompleteScope = 1 " autocomplete with ::
let OmniCpp_SelectFirstItem = 2 " select first item (but don't insert)
let OmniCpp_NamespaceSearch = 2 " search namespaces in this and included files
let OmniCpp_ShowPrototypeInAbbr = 1 " show function prototype in popup window
let OmniCpp_GlobalScopeSearch=1 " enable the global scope search
let OmniCpp_DisplayMode=1 " Class scope completion mode: always show all members
"let OmniCpp_DefaultNamespaces=["std"]
let OmniCpp_ShowScopeInAbbr=1 " show scope in abbreviation and remove the last column
let OmniCpp_ShowAccess=1
"}}}

" PLUG: InterestingWords Settings {{{1
"InterestingWords
let g:interestingWordsDefaultMappings = 0
nnoremap <silent> <leader>k :call InterestingWords('n')<cr>
vnoremap <silent> <leader>k :call InterestingWords('v')<cr>
nnoremap <silent> <leader>l :call UncolorAllWords()<cr>
nnoremap <silent> <leader>n :call WordNavigation(1)<cr>
nnoremap <silent> <leader>N :call WordNavigation(0)<cr>
"let g:interestingWordsGUIColors = ['#8CCBEA', '#A4E57E', '#FFDB72', '#FF7272', '#FFB3FF', '#9999FF']
"let g:interestingWordsTermColors = ['154', '121', '211', '137', '214', '222']
let g:interestingWordsRandomiseColors = 1
"}}}

" PLUG: color pair Settings {{{1
let g:rainbow_active = 1
let g:rainbow_conf = {
\   'guifgs': ['royalblue3', 'darkorange3', 'seagreen3', 'firebrick'],
\   'ctermfgs': ['darkblue', 'darkyellow', 'darkcyan', 'darkmagenta'],
\   'operators': '_,\|+\|-_',
\   'parentheses': ['start=/(/ end=/)/ fold', 'start=/\[/ end=/\]/ fold', 'start=/{/ end=/}/ fold'],
\   'separately': {
\       '*': {},
\       'tex': {
\           'parentheses': ['start=/(/ end=/)/', 'start=/\[/ end=/\]/'],
\       },
\       'css': 0,
\   }
\}
"}}}

" PLUG: ale Settings {{{1
let g:ale_linters_explicit = 1
let g:ale_completion_delay = 500
let g:ale_echo_delay = 20
let g:ale_lint_delay = 500
let g:ale_echo_msg_format = '[%linter%] %code: %%s'
let g:ale_lint_on_text_changed = 'normal'
let g:ale_lint_on_insert_leave = 1
let g:airline#extensions#ale#enabled = 1

let g:ale_c_gcc_options = '-Wall -O2 -std=c99'
let g:ale_cpp_gcc_options = '-Wall -O2 -std=c++14'
let g:ale_c_cppcheck_options = ''
let g:ale_cpp_cppcheck_options = ''
noremap <silent> <leader>w :ALENext<cr>
nnoremap <silent> <leader>e :ALEPrevious<cr>
"}}}

" copy : "+y {{{1
map <c-c> "+y
"}}}

" PLUG: myself Settings {{{1
" plugin shortcuts
function! RunShell(Msg, Shell)
	echo a:Msg . '...'
	call system(a:Shell)
	echon 'done'
endfunction

func AddPythonComment()
    call append(line("."),"print('File:'+sys._getframe().f_code.co_filename+' func:'+sys._getframe().f_code.co_name+' +'+str(sys._getframe().f_lineno))")
    call append(line(".")+1,"print('debug:')")
endfunc

func AddComment()
    call append(line("."),"/*TAG: Modified/Added/Deleted by yanzhongqian".strftime("%Y-%m-%d").",fix mantis XXX")
    call append(line(".")+1,"issue :")
    call append(line(".")+2,"cause :")
    call append(line(".")+3,"*/")
endfunc

func AddFuncComment()
    let s:line = getline(line(".")+1)
    let s:re_value = split(s:line)[0]
    let s:func_name_para = split(s:line)[1]
    let s:func_name = split(s:func_name_para, '(')[0]
    let s:func_para_list = split(split(s:line, '(')[1][0:-2], ',')
    let s:func_para_cnt = len(s:func_para_list)

    call append(line("."),    "/* Function Name:")
    call append(line(".")+1,  " *      ".s:func_name)
    call append(line(".")+2,  " * Description:")
    call append(line(".")+3,  " *      xxx")
    call append(line(".")+4,  " * Input:")
    for s:cnt in range(0, s:func_para_cnt - 1)
        call append(line(".")+s:cnt+5,  " *      ".trim(s:func_para_list[s:cnt]))
    endfor
    call append(line(".")+s:func_para_cnt+5,  " * Output:")
    call append(line(".")+s:func_para_cnt+6,  " *      None")
    call append(line(".")+s:func_para_cnt+7,  " * Return:")
    call append(line(".")+s:func_para_cnt+8,  " *      ".s:re_value)
    call append(line(".")+s:func_para_cnt+9, " */")
endfunc

" it's better to add ! in func defination, ! in exe represent extern call
func! CompileRunGcc()
exec "w"
exec "!gcc % -o %<"
exec "! ./%<"
endfunc

nmap <leader>1 :call AddPythonComment()<cr>
nmap <leader>4 oprintf("\033[31mDebug: file:%s, func:%s, line=%d \033[0m \n",__FILE__,__FUNCTION__,__LINE__);<ESC>0
nmap <leader>5 oprintf("\033[32mDebug: file:%s, func:%s, line=%d \033[0m \n",__FILE__,__FUNCTION__,__LINE__);<ESC>0
nmap <leader>6 oprintf("Debug:func:%s,line=%d\n",__FUNCTION__,__LINE__);<ESC>0
nmap <leader>7 :call AddFuncComment()<cr>
nmap <leader>8 :call AddComment()<cr>
"--c++-kinds=+p  :func declare  --fields=+iaS s:sign cscope -Rbq q:Speed up indexing
"nmap  <F9> :call RunShell("Generate tags and cscope", "ctags -R --c++-kinds=+p --fields=+iaS --extra=+q . && cscope -Rbq")<cr>:UpdateTypesFileOnly<cr>:q<cr>
nmap  <F9> :call RunShell("Generate tags and cscope", "ctags -R --fields=+ia --extra=+q && cscope -Rbq")<cr>:UpdateTypesFileOnly<cr>:q<cr>
noremap <F5> :tabnew ~/.vimrc
noremap <F3> :call CompileRunGcc()<CR>
"}}}

" 可以在Normal Mode和Visual/Select Mode下，利用Tab键和Shift-Tab键来缩进文本{{{1
nmap <tab> :><cr>
nmap <s-tab> :<cr>
vmap <tab> >gv
vmap <s-tab> <gv
nmap <C-n> :tabnew .<cr>
"删除空格行：
nnoremap tl :g/^$/d<cr>:noh<cr>
"删除行首空格：
nnoremap th :%s/^\s*//g<cr>:noh<cr>
"删除行尾空格：
nnoremap tt :%s/\s*$//g<cr>:noh<cr>
"}}}

" 当新建 .h .c .hpp .cpp .mk .sh等文件时自动调用SetTitle 函数{{{1
autocmd BufNewFile *.[ch],*.hpp,*.cpp,Makefile,*.mk,*.sh,*.py exec ":call SetTitle()"
" 加入注释
func SetComment()
    call setline(1,"/*================================================================")
    call append(line("."),   "*   Copyright (C) ".strftime("%Y")." Sangfor Ltd. All rights reserved.")
    call append(line(".")+1, "*   ")
    call append(line(".")+2, "*   filename：".expand("%:t"))
    call append(line(".")+3, "*   creator ：Zhongqianyan")
    call append(line(".")+4, "*   data    ：".strftime("%Y年%m月%d日"))
    call append(line(".")+5, "*   descript：")
    call append(line(".")+6, "*")
    call append(line(".")+7, "================================================================*/")
    call append(line(".")+8, "")
    call append(line(".")+9, "")
endfunc

" 加入shell,Makefile注释
func SetComment_sh()
    call setline(3, "#================================================================")
    call setline(4, "#   Copyright (C) ".strftime("%Y")." Sangfor Ltd. All rights reserved.")
    call setline(5, "#   ")
    call setline(6, "#  filename：".expand("%:t"))
    call setline(7, "#  creator ：Zhongqianyan")
    call setline(8, "#  data    ：".strftime("%Y年%m月%d日"))
    call setline(9, "#  descript：")
    call setline(10, "#")
    call setline(11, "#================================================================")
    call setline(12, "")
    call setline(13, "")
endfunc
" 加入python注释
func SetComment_py()
    call setline(3, "# ")
    call setline(4, "# Author:       yanzhongqian")
    call setline(5, "# ")
    call setline(6, "# Created Time: ".strftime("%c"))
    call setline(7, "# ")
    call setline(8, "# FileName:     ".expand("%"))
    call setline(9, "# ")
    call setline(10, "# Description:  ")
    call setline(11, "# ")
    call setline(12, "# ChangeLog:")
endfunc

" 定义函数SetTitle，自动插入文件头
func SetTitle()
    if &filetype == 'make'
        call setline(1,"")
        call setline(2,"")
        call SetComment_sh()

    elseif &filetype == 'python'
        call setline(1, "#!env python")
        call setline(2, "#coding=utf-8")
        call SetComment_py()

    elseif &filetype == 'sh'
        call setline(1,"#!/bin/bash")
        call setline(2,"")
        call SetComment_sh()

    else
         call SetComment()
         if expand("%:e") == 'hpp'
          call append(line(".")+10, "#ifndef _".toupper(expand("%:t:r"))."_H")
          call append(line(".")+11, "#define _".toupper(expand("%:t:r"))."_H")
          call append(line(".")+12, "#ifdef __cplusplus")
          call append(line(".")+13, "extern \"C\"")
          call append(line(".")+14, "{")
          call append(line(".")+15, "#endif")
          call append(line(".")+16, "")
          call append(line(".")+17, "#ifdef __cplusplus")
          call append(line(".")+18, "}")
          call append(line(".")+19, "#endif")
          call append(line(".")+20, "#endif //".toupper(expand("%:t:r"))."_H")
         elseif expand("%:e") == 'h'
          call append(line(".")+10, "#ifndef _".toupper(expand("%:t:r"))."_H")
          call append(line(".")+11, "#define _".toupper(expand("%:t:r"))."_H")
          call append(line(".")+12, "#endif //".toupper(expand("%:t:r"))."_H")
         elseif &filetype == 'c'
          call append(line(".")+10,"#include \"".expand("%:t:r").".h\"")
         elseif &filetype == 'cpp'
          call append(line(".")+10, "#include \"".expand("%:t:r").".h\"")
         endif
    endif
endfunc
"}}}
